import { GameBrandNum, ServerBrand } from '@/config/eunm'
import { useStore } from '@/stores/index'
import { useRoute } from 'vue-router'
// 游戏的带品牌
export function GamePlatform(game_id: number) {
  const indexStore = useStore()
  return selectToLabel(GameBrandNum, selectToLabel(indexStore.gameArray, game_id, 'platform_backend_echo', 'value'))
}
// 封禁的品牌
export function GamePlatformDisabled(game_id: number) {
  let disabled=[9],indexStore = useStore();
  if(disabled.find((item:any) => item == selectToLabel(indexStore.gameArray, game_id, 'platform', 'value'))){
    return true
  }else{
    return false
  }
}
// 对应商户的货币
export function AgentCurrency(agent_id: number) {
  const indexStore = useStore()
  return ( selectToLabel(indexStore.currentArray, selectToLabel(indexStore.agentArray, agent_id, 'currency', 'value')) +
    '(' +
    selectToLabel(
      indexStore.currentArray,
      selectToLabel(indexStore.agentArray, agent_id, 'currency', 'value'),
      'type',
      'value'
    ) +
    ')' +
    '-' +
    selectToLabel(
      indexStore.currentArray,
      selectToLabel(indexStore.agentArray, agent_id, 'currency', 'value'),
      'remark',
      'value'
    )
  )
}
// 对应商户的货币汇率
export function CurrencyExchange (agent_id: number) {
  const indexStore = useStore()
  return selectToLabel(
    indexStore.exchangeList, selectToLabel(indexStore.agentArray, agent_id, 'currency', 'value'), 'status', 'value'
  )
}
// 对应服务器域名校验【美服-亚服】参数配置
export function OperatorServerBrand(type:string) {
  return selectToLabel(ServerBrand,location.host,type,'value')
}
// 数值颜色
export function colorClass(num: any) {
  let color = 'colorGre'
  if (Number(num) <= 0) {
    color = 'colorRed'
  }
  return color
}
// 存取页面查询条件
export function getQueryCache(query: any) {
  const indexStore = useStore()
  const route = useRoute()
  if(selectToLabel(indexStore.queryArray,route.name)){
    return selectToLabel(indexStore.queryArray,route.name)
  }else{
  }
  return query
}

// 下拉框  value => label
export function selectToLabel(arr: any, val: any, label?: string, value?: string){
  if (label) {
    let list = arr.filter((item: any) => item[value ?? ''] == val)
    if (!list.length) return ''
    return list[0][label]
  } else {
    let list = arr.filter((item: any) => item.value == val)
    if (!list.length) return ''
    return list[0].label
  }
}
// 数组每x个元素 分一组
export function arrayGroup(arr: any, chunkSize: number) {
  return arr.reduce((chunks: any, item: any, i: any) => {
    const chunkIndex = Math.floor(i / chunkSize)
    if (!chunks[chunkIndex]) {
      chunks[chunkIndex] = []
    }
    chunks[chunkIndex].push(item)
    return chunks
  }, [])
}
// 按照数组对象的某个值去重
export function setObjectArray(arr: any, key: string) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i][key] == arr[j][key]) {
        arr.splice(j, 1)
        j--
      }
    }
  }
  return arr
}

// 判断A数组是否包含B数组的值
export function ArrayContain(arr:any, data:any) {
  let newVal = new Set(data);
  let newAirArr = new Set(arr);
  let intersectionSet = new Set(
    [...newVal].filter((x) => newAirArr.has(x))
  );
  if (intersectionSet.size) {
    return true
  } else {
    return false
  }
}
// 判断A数组是否包含X值
export function ArrayExist(arr:any, data:any) {
  if(arr.find((item:any) => item == data)){
    return true
  }else{
    return false
  }
}
// 按照数组排序
export function sortArray(arr: any, type: string) {
  return arr.sort(function (a: any, b: any) {
    if (type == 'desc') {
      return Number(a) > Number(b) ? -1 : Number(a) < Number(b) ? 1 : 0
    } else {
      return Number(a) < Number(b) ? -1 : Number(a) > Number(b) ? 1 : 0
    }
  })
}
// 按照数组对象的某个值排序
export function sortObjectArray(arr: any, key: string, type: string) {
  return arr.sort(function (a: any, b: any) {
    var x = a[key]
    var y = b[key]
    if (type == 'desc') {
      return x > y ? -1 : x < y ? 1 : 0
    } else {
      return x < y ? -1 : x > y ? 1 : 0
    }
  })
}
// 数字数组求和
export function ArrayReduce(arr: any) {
  return arr.reduce((acc: number, curr: number) => acc + curr, 0)
}
// 字符串替换
export function StringReplace(srting:string, goal:string, replace:string) {
  return srting.split(goal).join(replace)
}
// 数字数组求幂
export function NumberPower(number: number) {
  let result = [];
  for (let i = 31; i >= 0; i--) {
    if (number & (1 << i)) {
      result.push(1 << i);
      number = number ^ (1 << i); // 异或运算移除已经加入的2的幂
    }
  }
  return result
}

// 获取表格存储的表头   list 有值就是存储  没有就是取值
export function getTableHeader(list?: any) {
  let th = localStorage.getItem('table-header')
    ? JSON.parse(localStorage.getItem('table-header') ?? '')
    : ''
  let path = localStorage.getItem('path') ?? ''
  if (list) {
    if (th) {
      th[path] = list
      localStorage.setItem('table-header', JSON.stringify(th))
    } else {
      interface MyObject {
        [key: string]: any
      }
      let obj: MyObject = {}
      obj[path] = list
      localStorage.setItem('table-header', JSON.stringify(obj))
    }
  } else {
    if (!th) return ''
    return th[path]
  }
}
// 自定义指令  实现按钮权限控制
export function authDevice(app: any) {
  app.directive('permiss', {
    mounted(el: any, binding: any, vnode: any) {
      const permission = localStorage.getItem('permission')
        ? JSON.parse(localStorage.getItem('permission') ?? '')
        : []
      const { value } = binding
      if (permission.indexOf(value) < 0) {
        el.style.display = 'none'
      }
    }
  })
}
// 防抖
export function throttle(fn: Function, wait: number) {
  let timer: any
  return function (query?: any) {
    if (timer != null) return
    // @ts-ignore
    const context = this
    const args = arguments
    fn.apply(context, args)
    timer = setTimeout(() => {
      timer = null
    }, wait)
  }
}
// 获取路径上的IP (全称：http://*******)
export function getUrlIp(path?:string) {
  if(path){
    return path
  }
  const url = window.location.href
  const paramsString = url.split('?')[1]
  const table = {} as any
  if (paramsString?.length) {
    const paramsArr = paramsString.split('&')
    paramsArr.forEach((pa) => {
      const itemArr = pa.split('=')
      if (itemArr.length === 2) {
        table[itemArr[0]] = itemArr[1]
      }
    })
  }
  if (table.ip) {
    sessionStorage.setItem('ip',table.ip)
    return table.ip + '/api'
  } else {
    if(sessionStorage.getItem('ip')){
      return sessionStorage.getItem('ip') + '/api'
    }else{
      return OperatorServerBrand('request')
    }
  }
}
// 语言转换
export const LangConversion = (arr: { label: string; value: number }[], val: string) => {
  if (!val) return ''
  let valArr = val.split(',')
  let str: string[] = []
  arr?.forEach((item) => {
    valArr?.forEach((v) => {
      if (item.value == +v) {
        str.push(item.label)
      }
    })
  })
  return str.join()
}
// 校验输入域名限制
const FormalDress = [
  { label:true,value:'manage.wbnr.xyz' },
  { label:true,value:'manage-gm.wbnr.xyz' },
  { label:true,value:'manage-as.wbnr.xyz' },
  { label:true,value:'manage-gmas.wbnr.xyz' },
  { label:true,value:'manage-ct.wbnr.xyz' },
]
export function removeDomain(val: string) {
  if (!val) return ''
  // 正式服校验--域名是否携带 https:// 然后去除
  if (selectToLabel(FormalDress,location.host)) {
    if (val.includes('https://')) {
      val = val.substring(8, val.length)
    }
  }
  return val
}
export function domainVerification(val: string) {
  if (!val) return ''
  if (selectToLabel(FormalDress,location.host)) {
    if (!val.includes('https://')) {
      val = 'https://' + val
    }
  }
  return val
}

// 【逗号-分号】的字段处理成数组
export function setStrToArr(str: string) {
  let arr: any[] = []
  if (str.split(';').length > 1) {
    //是否有；分割
    arr = str.split(';')
    arr?.forEach((v, h) => {
      arr[h] = v.split(',') //处理成为二维数组 [[4,6],[3,5]]
    })
  } else {
    arr = str.split(',')
  }
  return arr
}
// 【 - 】分号的字段处理成数组
export function setArrCross(str: string) {
  let arr: any[] = []
  if (str.split('-').length > 1) {
    //是否有-分割
    arr = str.split('-')
    arr?.forEach((v, h) => {
      arr[h] = v.split(';') //处理成为二维数组 [[4,6],[3,5]]
    })
    arr?.forEach((v) => {
      v?.forEach((item: any, h: number) => {
        //处理成为三维数组 [1,2,[4,6],[3,5]]
        if (item.split(',').length > 1) {
          v.splice(h, 1, item.split(','))
        }
      })
    })
  }
  return arr
}
// 【 ; 】分号区分处理成数组
export function setSemicolonToArr(str: string) {
  let arr: any[] = []
  arr = str.split(';')
  arr?.forEach((v, h) => {
    if (v.length) {
      arr[h] = v.split(',') //处理成为二维数组 [[4,6],[3,5]]
    } else {
      arr.splice(h, 1)
    }
  })
  return arr
}
// 【 , 】逗号区分处理成数组
export function setCommaToArr(str: string) {
  let arr: any[] = []
  arr = str.split(',')
  return arr
}
export function setCommaNumberToArr(str: string) {
  let arr: any[] = [],
    num: any[] = []
  arr = str.split(',')
  arr.forEach((item: string) => {
    num.push(Number(item))
  })
  return num
}
// 【逗号】区分处理成数组(min max)
export function setStrMinMax(str: string) {
  let arr: any[] = [],
    newArr: any[] = []
  arr = str.split(',')
  newArr.push({ min: Number(arr[0]), max: Number(arr[1]) })
  return newArr
}
// 对象处理成【 , 】逗号分割的字符串
export function setObjStr(obj: any) {
  let str = '', key = Object.keys(obj);
  key?.forEach((item: any) => {
    str += obj[item] + ','
  })
  return str.substring(0, str.length - 1)
}
// 数组处理成【 ; 】分号分割的字符串
export function setArrStr(arr: any) {
  let str = ''
  arr?.forEach((item: any) => {
    str += setObjStr(item) + ';'
  })
  return str.substring(0, str.length - 1)
}
// 数组处理成【 , 】逗号分割的字符串
export function setArrCommaStr(arr: any) {
  let str = ''
  arr?.forEach((item: any) => {
    str += setObjStr(item) + ','
  })
  return str.substring(0, str.length - 1)
}